package tweeks.user.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import tweeks.user.domain.Group;
import tweeks.user.domain.Permission;
import tweeks.user.domain.User;
import tweeks.user.persistence.UserMapper;

@Service("UserNormalService")
public class UserNormalService implements UserService, UserDetailsService {
	
	@Resource(name="UserMapper")
	private UserMapper userMapper;

	public void createUser(UserDetails user) {
		userMapper.createUser(user);
		userMapper.createUserGroup(user);
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		List<UserDetails> users = userMapper.loadUserByUsername(username);
		
		User user = (User) users.get(0);
		
		List<Map<String, String>> auths = userMapper.loadGroupAuthorities(username);
		
		List<GrantedAuthority> dbAuths = new ArrayList<GrantedAuthority>();
		for (Map<String, String> item : auths) {
			dbAuths.add(new SimpleGrantedAuthority(item.get("PERMISSION_CODE")));
		}
		
		return new User(user.getLoginId(), user.getEmail()
				, user.getPassword(), user.getFirstName()
				, user.getLastName(), true
				, true, true
				, true, dbAuths);
	}

	@Override
	public void updateUser(UserDetails user) {
		userMapper.updateUser(user);
		userMapper.updateUserGroup(user);
	}


	@Override
	public void deleteUser(String id) {
		userMapper.deleteUserGroup(id);
		userMapper.deleteUser(id);
	}

	@Override
	public void changePassword(String oldPassword, String newPassword) {
		
	}

	@Override
	public boolean userExists(String username) {
		return false;
	}

	@Override
	public List<UserDetails> selectUser(UserDetails user) {
		return userMapper.selectUser(user);
	}

	@Override
	public List<Group> selectGroup(Group group) {
		return userMapper.selectGroup(group);
	}

	@Override
	public List<Permission> selectPermission(Permission permission) {
		return userMapper.selectPermission(permission);
	}
}